﻿using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.IO;
using System.Linq;
using System.Text;
using Thor.Common;

namespace Thor.Repository.EntFx
{
    public class ProviderRepository : RepositoryBase, IProviderRepository
    {
        #region Constructors

        public ProviderRepository(Dictionary<string, object> repositoryParameters)
            : base(repositoryParameters) { }

        #endregion

        #region IProviderRepository Members

        public void InsertFiles(List<ProviderFile> files)
        {
            if (files != null && Model != null)
            {
                DeleteFiles();

                foreach (var file in files)
                {
                    CalAssemblyEntity entity = new CalAssemblyEntity();

                    if (file.Stream != null && file.Stream is MemoryStream)
                    {
                        MemoryStream memoryStream = (MemoryStream)file.Stream;
                        entity.Bytes = memoryStream.ToArray();
                    }

                    entity.Name = file.Name;
                    Model.AddToCalAssemblyEntities(entity);
                    Model.SaveChanges();
                }
            }
        }

        public void UpdateFiles(List<ProviderFile> files)
        {
            if (files != null && Model != null)
            {
                InsertFiles(files);
            }
        }

        public void DeleteFiles()
        {
            if (Model != null)
            {
                var entities = Model.CalAssemblyEntities.ToList();

                if (entities != null)
                {
                    foreach (var entity in entities)
                    {
                        Model.DeleteObject(entity);
                        Model.SaveChanges();
                    }
                }
            }
        }

        public List<ProviderFile> FetchFiles()
        {
            if (Model != null)
            {
                var entities = Model.CalAssemblyEntities.ToList();

                if (entities != null)
                {
                    List<ProviderFile> result = new List<ProviderFile>();

                    foreach (var entity in entities)
                    {
                        ProviderFile file = new ProviderFile();
                        file.Bytes = entity.Bytes;
                        file.Name = entity.Name;
                        result.Add(file);
                    }

                    return result;
                }

                return null;
            }

            return null;
        }

        #endregion
    }
}